import { defineStore } from 'pinia'
import { userApi } from '../api/user'
import axios from 'axios'

export const useAuthStore = defineStore('auth', {
  state: () => ({
    user: JSON.parse(localStorage.getItem('user')) || null,
    token: localStorage.getItem('token') || null,
    loading: false
  }),

  getters: {
    isAuthenticated: (state) => !!state.token,
    isAdmin: (state) => state.user?.role === 'admin'
  },

  actions: {
    async login(credentials) {
      try {
        this.loading = true
        const { token, user } = await userApi.login(credentials)
        this.token = token
        this.user = user
        localStorage.setItem('token', token)
        localStorage.setItem('user', JSON.stringify(user))
        axios.defaults.headers.common['Authorization'] = `Bearer ${token}`
      } finally {
        this.loading = false
      }
    },

    async register(userData) {
      try {
        this.loading = true
        const { token, user } = await userApi.register(userData)
        this.token = token
        this.user = user
        localStorage.setItem('token', token)
        axios.defaults.headers.common['Authorization'] = `Bearer ${token}`
      } finally {
        this.loading = false
      }
    },

    async logout() {
      this.token = null
      this.user = null
      localStorage.removeItem('token')
      localStorage.removeItem('user')
      delete axios.defaults.headers.common['Authorization']
    },

    async fetchUser() {
      if (!this.token) return
      
      try {
        this.loading = true
        const user = await userApi.getCurrentUser()
        this.user = user
      } catch (error) {
        await this.logout()
        throw error
      } finally {
        this.loading = false
      }
    },

    async updateProfile(profileData) {
      try {
        this.loading = true
        const user = await userApi.updateProfile(profileData)
        this.user = user
      } finally {
        this.loading = false
      }
    },

    async updatePassword(passwordData) {
      try {
        this.loading = true
        await userApi.updatePassword(passwordData)
      } finally {
        this.loading = false
      }
    },

    updateUser(userData) {
      this.user = {
        ...this.user,
        ...userData
      };
      localStorage.setItem('user', JSON.stringify(this.user));
    }
  }
}) 